<?php
namespace app\common\model;
// 订单 处理业务
use app\common\service\Wechat;
use think\Db;
use think\facade\Config;
use think\facade\Env;
use think\facade\Log;
use wxzhifu\example\JsApiPay;
use wxzhifu\example\WxPayConfig;
use wxzhifu\lib\WxPayApi;
use wxzhifu\lib\WxPayException;
use wxzhifu\lib\WxPayUnifiedOrder;
use think\model\concern\SoftDelete;
use app\common\service\Yunpian;

class Order extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_order';
    // 主键ID
    protected $pk = 'order_id';

    // 软删除
    use SoftDelete;
    protected $deleteTime = 'is_del';
    protected $defaultSoftDelete = 1;

	//订单状态
	public static $statelist = [
		'1'=>'待支付',
		'2'=>'待发货',
		'3'=>'已发货',
		'4'=>'已完成',
		'5'=>'用户取消订单',
		'6'=>'订单退款',
		'7'=>'订单退货',
		'10'=>'售后中',
	];
	//支付状态
	public static $paystatelist = [
		'1' => '待支付',
		'2' => '已支付',
		'3' => '已取消',
	];

	/**
	 * @param array $where  // 查询的条件
	 * @param string $item  // 查询的参数
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*')
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

    function shops_order_list($cond,$orderby,$limit,$is_page = true,$ofield = ['o.*','s.shop_name','u.user_id','u.nick_name','a.*'],$dfield = ['*'])
    {
        $where = [];

        if(!empty($cond['shop_name'])){
            $where[] = ['s.shop_name','like','%'.$cond['shop_name'].'%'];
        }
//        if(!empty($cond['product_name'])){
//            $where[] = ['d.product_name','like','%'.$cond['product_name'].'%'];
//        }
        if(!empty($cond['shop_id'])){
            $where[] = ['o.shop_id','=',$cond['shop_id']];
        }
        if(!empty($cond['user_id'])){
            $where[] = ['o.user_id','=',$cond['user_id']];
        }
        if(!empty($cond['pay_status'])){
            $where[] = ['o.pay_status','=',$cond['pay_status']];
        }
        if(!empty($cond['order_status'])){

            if($cond['order_status'] == 10){
                $where[] = ['o.order_status','in','6,10'];
            }else{
                $where[] = ['o.order_status','=',$cond['order_status']];
            }
        }
        if(!empty($cond['order_type'])){
            if($cond['order_type'] == 3){
                $where[] = ['o.order_type','=',$cond['order_type']];
            }else{
                $where[] = ['o.order_type','in',"1,2"];
            }

        }
        if(!empty($cond['order_types'])){
            $where[] = ['o.order_type','=',$cond['order_types']];
        }
        if(!empty($cond['class_ids'])){
            $where[] = ['o.order_type','in',$cond['class_ids']];
        }
        if(!empty($cond['is_comment'])){

            if($cond['is_comment'] == 2){
                $where[] = ['o.is_comment','=', 0];
            }elseif ($cond['is_comment'] == 1){
                $where[] = ['o.is_comment','=', 1];
            }
        }

        if(!empty($cond['time'])){
            $array = explode(' - ',input('get.time'));
            $start = strtotime($array[0]." 00:00:00");
            if($array[0] == $array[1]){
                $end = strtotime($array[0]." 23:59:59");
            } else {
                $end = strtotime($array[1]." 00:00:00");
            }
            $where[] = ['o.order_time','between',[$start,$end]];
        }

        $jion = [
            ['ddt_shops s','o.shop_id = s.shop_id'],
            ['ddt_user u','o.user_id = u.user_id'],
            ['ddt_address a','o.address_id = a.address_id'],
            ['ddt_express f','o.express_id = f.express_id'],
        ];



        $OrderDetailModel = new OrderDetail();
        if(!empty($cond['product_name'])){
            $orderids = $OrderDetailModel
                ->where('user_id','=',$cond['user_id'])
                ->where('product_name','like','%'.$cond['product_name'].'%')
                ->distinct(true)
                ->column('order_id');
            $where[] = ['o.order_id','in',implode(',',$orderids)];
        }

//
        $data = $this
            ->alias('o')
            ->field($ofield)
            ->where($where)
            ->leftJoin($jion)
            ->order($orderby)
            ->paginate($limit);
//        echo $this->getLastSql();die;
        if($is_page){
            $page = $data->render();
        }else{
            $page = [
                "total"=> $data->total(),
                "per_page"=> $data->listRows(),
                "current_page"=> $data->currentPage(),
                "last_page"=> $data->lastPage(),
            ];
        }

        //处理一个主订单表对应多订单详情表逻辑
        if($data->toArray()){
            $data = $data->toArray()['data'];
            $lists = array_column($data,null,'order_id');
            $order_ids = implode(',',array_column($data,'order_id'));
            $DetailList = $OrderDetailModel->field($dfield)->where([
                ['order_id','in',$order_ids]
            ])->select()->toArray();
            foreach($DetailList as $key => $value){
                $lists[$value['order_id']]['number'] = $lists[$value['order_id']]['number']??0 + $value['quantity'];
                $lists[$value['order_id']]['children'][] = $value;
            }
            $data = array_values($lists);

            foreach ($data as $key => $val){
                if($val['is_show'] == 1){
                    $rs = $this->where('order_id', $val['order_id'])->update(['is_show' => 2]);
                }
            }
        }
        return ['data'=>$data,'page'=>$page];
    }

    function get_list($cond, $orderby, $item)
    {

        $where = null;

        if(!empty($cond['order_type'])){
            $where[] = ['order_type', '=', $cond['order_type']];
        }

        if(!empty($cond['shop_id'])){
            $where[] = ['shop_id', '=', $cond['shop_id']];
        }

        if(!empty($cond['pay_status'])){
            $where[] = ['pay_status', '=', $cond['pay_status']];
        }

        if(!empty($cond['order_status'])){
            $where[] = ['order_status', '=', $cond['order_status']];
        }
        if(!empty($cond['is_comment']) && $cond['is_comment'] == 2){
            $where[] = ['is_comment', '=', 0];
        }

        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }

    //  商家获取订单详情
    function shops_order_details($orderId)
    {
        $rs = Db::table('ddt_orderdetail')
            ->alias('od')
            ->join('ddt_products p','p.product_id = od.product_id')
            ->join('ddt_products_type pt','pt.type_id = p.type_id')
//            ->join('ddt_products_stock ps','od.p_s_id = ps.p_s_id')
            ->field('od.*,pt.type_name')
            ->where('order_id',$orderId)
            ->select();

        return $rs;
    }

	// 商铺报表
    function ShopsReportFormList($get,$limit)
    {
        $shopModel = new Shops();

//        $cond['approved'] = 1;
//        $cond['state'] = 1;
//        $cond['shop_name'] = $get['shop_name'];
//        $cond['shop_id'] = $get['shop_id'];


        $where = [
            ['approved', '=', 1],
            ['state', '=', 1],
        ];
        if(!empty($get['shop_name'])){
            $where[] = ['shop_name','like',"%".$get['shop_name']."%"];
        }
        if(!empty($get['shop_type'])){
            $where[] = ['shop_type','=',$get['shop_type']];
        }

        if(!empty($get['shop_id'])){
            $where[] = ['shop_id', '=',$get['shop_id']];
        }

        $field = "shop_id,shop_name,shop_type,province,city,area,address,shop_manager";

        // 分页循环添加数据  （十一）
        $rs = $shopModel->where($where)->field($field)->order('add_time desc')->paginate($limit)->each(function ($item, $key){
            $shopwhere = [
                ['shop_id','=', $item['shop_id']],
                ['order_status', 'in', '2,3,4'],
                ['pay_status', '=', 2],
                ['order_type', 'in', '1,3']
            ];
            $rs = $this->where($shopwhere)->field('sum(pay_amount) as money,count(order_id) as count')->select()->toArray()[0];
            $item['count'] = $rs['count'];
            $item['money'] = $rs['money'];
        });
        return $rs;
    }

//    处理订单插入数据
    function placecreateorder($user,$ids,$settlemnt,$address_id,$receive_id = 0){
        $cartModel = new Cart();
        //查询商品信息
		$products = $cartModel
            ->alias('cart')
            ->field('cart.cart_id,cart.quantity,cart.p_s_id,cart.product_id,p.shop_id,p.product_name,p.price,p.mprice,p.mprice,p.express_fee,p.imageurl,s.p_s_name')
            ->where([
                ['cart.user_id','=',$user['user_id']],
                ['p.state','=',1],
                ['p.approved','=',2],
                ['p.is_online','=',1],
                ['cart.cart_id','in',$ids],
            ])
            ->where("s.stock >= cart.quantity")
            ->leftJoin('ddt_products p',"cart.product_id = p.product_id")
            ->leftJoin('ddt_products_stock s',"cart.p_s_id = s.p_s_id")
            ->select()->toArray();
		$coupon['discount'] = 0.00;
        if($receive_id){
            $CouponReceiveModel = new CouponReceive();
            $coupon = $CouponReceiveModel->where(['receive_id'=>$receive_id,'user_id'=>$user['user_id'],'is_use'=>1])->find()->toArray();
        }

		$newshoplist = [];
        $utype = 'mprice';
		foreach($products as $key => $value){
            $newshoplist[$value['shop_id']]['product'][] = $value;
//            $newshoplist[$value['shop_id']]['products_amount'] += calculate([$value[$utype],$value['quantity']],'*');
            if(isset($newshoplist[$value['shop_id']]['products_amount'])){
                $newshoplist[$value['shop_id']]['products_amount'] += calculate([$value[$utype],$value['quantity']],'*');
            } else {
                $newshoplist[$value['shop_id']]['products_amount'] = calculate([$value[$utype],$value['quantity']],'*');
            }
//            $newshoplist[$value['shop_id']]['express_fee'] += $value['express_fee'];
            if(isset($newshoplist[$value['shop_id']]['express_fee'])){
                $newshoplist[$value['shop_id']]['express_fee'] += $value['express_fee'];
            } else {
                $newshoplist[$value['shop_id']]['express_fee'] = $value['express_fee'];
            }
            $newshoplist[$value['shop_id']]['receive_id'] = $receive_id;
            $newshoplist[$value['shop_id']]['coupon_amount'] = $coupon['discount'];
            $newshoplist[$value['shop_id']]['order_amount'] = $newshoplist[$value['shop_id']]['products_amount'];
            $newshoplist[$value['shop_id']]['pay_amount'] = $newshoplist[$value['shop_id']]['products_amount'] + $newshoplist[$value['shop_id']]['express_fee'];
//            var_dump($newshoplist);die;

//            只做单个商家的下单处理（暂时）
            $newshoplist[$value['shop_id']]['pay_amount'] = calculate([$newshoplist[$value['shop_id']]['pay_amount'],$newshoplist[$value['shop_id']]['coupon_amount']],'-');
        }
//		var_dump($newshoplist);die;
//        var_dump(123);die;
        $detailModel = new \app\common\model\OrderDetail();
		$stockModel = new ProductStock();
		$paymentModel = new Payments();
        $time = time();
		$orders = [];
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $insertpayments = [
            "user" => $user,
            "data" => $settlemnt,
        ];
		$paymentModel->startTrans();
		$pay_id = $paymentModel->insertpayments($insertpayments,"order");
		if($pay_id === false){
            $paymentModel->rollback();
            $this->setError(-1,'插入购买记录失败');
            return $result;
        }
		foreach($newshoplist as $key => $value){
//		    var_dump($value);die;
		    $insertorder['data'] = $value;
		    $insertorder['shop_id'] = $key;
		    $insertorder['order_type'] = 1;
		    $insertorder['order_time'] = $time;
		    $insertorder['user_id'] = $user['user_id'];
		    $insertorder['address_id'] = $address_id;
		    $insertorder['payments_id'] = $pay_id;
		    $insertorder['receive_id'] = $receive_id??0;
            $orderid = $this->insertorder($insertorder);

            if($orderid === false){
                $paymentModel->rollback();
                $this->setError(-1,'订单生成失败');
                return $result;
            }
//            var_dump($orderid);
            $orders[] = $orderid;
//            var_dump($orders);die;

            $param = [];
            $i = 0;
            foreach($value['product'] as $k => $v){
//                echo "<prev>";
//                var_dump($v);

                $param_detail[$i]['user_id'] = $user['user_id'];
                $param_detail[$i]['order_id'] = $orderid;
                $param_detail[$i]['product_id'] = $v['product_id'];
                $param_detail[$i]['product_name'] = $v['product_name'];
                $param_detail[$i]['p_s_id'] = $v['p_s_id'];
                $param_detail[$i]['p_s_name'] = $v['p_s_name'];
                $param_detail[$i]['cover_url'] = $v['imageurl'];
                $param_detail[$i]['quantity'] = $v['quantity'];
                $param_detail[$i]['price'] = $v['price'];
                $param_detail[$i]['sale_price'] = $v[$utype];
                $param_detail[$i]['growth_coin'] = 0;
                $param_detail[$i]['amount'] = calculate([$v[$utype],$v['quantity']],'*');
                $param_detail[$i]['add_time'] = time();
                $param_detail[$i]['update_time'] = time();

                $i += 1;

                $reduce_rs = $stockModel->reducestock($v['product_id'],$v['p_s_id'],$v['quantity']);
//                var_dump($reduce_rs);die;
                if($reduce_rs === false){
                    $paymentModel->rollback();
                    $this->setError(-1,'商品库存减少失败');
                    return $result;
                }
            }

            $res = $detailModel->saveAll($param_detail);
            if($res === false){
                $paymentModel->rollback();
                $this->setError(-1,'订单商品信息记录失败');
                return $result;
            }

        }

        $paymentModel->commit();
		$cartModel = new Cart();
		$cartModel->delcart($user['user_id'],$ids);
//		echo "<prev>";
//		var_dump($orders);die;
//		var_dump($newshoplist);die;
//		var_dump($products);
//        var_dump($shop_ids);die;
        $result['code'] = true;
        $result['data'] = [
            'orders' => $orders,
            'paymentsid' => $pay_id,
        ];
        return $result;
    }

//    订单插入操作
    function insertorder($insertdata){
        $addressModel = new Address();

        $address = $addressModel->getOne(['address_id' => $insertdata['address_id']],'name,phone,province_name,city_name,area_name,street_name,detail');

        if(!isset($insertdata['order_time'])){
            $insertdata['order_time'] = time();
        }
        $orderno = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $data = [
            'shop_id' => $insertdata['shop_id'],
            'order_type' => $insertdata['order_type'],
            'products_amount' => $insertdata['data']['products_amount'],
            'receive_id' => $insertdata['receive_id'],
            'coupon_amount' => $insertdata['data']['coupon_amount'],
            'express_fee' => $insertdata['data']['express_fee'],
            'order_amount' => $insertdata['data']['order_amount'],
            'pay_amount' => $insertdata['data']['pay_amount'],
            'order_time' => $insertdata['order_time'],
            'orderno' => $orderno,
            'user_id' => $insertdata['user_id'],
            'address_id' => $insertdata['address_id'],
            'payments_id' => $insertdata['payments_id'],
            'receive_name' => $address['name'],
            'p_c_a' => $address['province_name'].' '.$address['city_name'].' '.$address['area_name'].' '.$address['street_name'],
            'r_address' => $address['detail'],
            'r_phone' => $address['phone'],
            'format_time' => date("Y-m-d H:i:s", time()),
        ];
        $rs = $this->save($data);
        if ($rs === false) {
            return false;
        }
        $orderid = $this->order_id;
        return $orderid;
    }

//    订单微信支付
    function wxpay($user,$paymentsid,$wxconfig,$notifyurl,$pay_end = 1,$tradetype = "JSAPI")
    {

//        $attach = JWTUtil::encode(implode(',',$orderids),$key);
//        var_dump($attach);die;
        $paymentsModel = new Payments();
        $where = [
            'payments_id' => $paymentsid
        ];
        $payments = $paymentsModel->where($where)->find();

        if($pay_end == 1){// 下单端不同参数不同 1-h5下单支付 2-小程序下单支付
            $openId = $user['wx_openid'];
            $attch['pay_end'] = '1';
        } else {
            $openId = $user['applets_openid'];
            $attch['pay_end'] = '2';
        }
        $attch = json_encode($attch,true);
        $notifyurl = request()->domain().$notifyurl;
        $input = new WxPayUnifiedOrder();
        $input->SetBody("paymentsid_".$paymentsid);
//        $input->SetAttach("paymentsid_".$paymentsid);
        $input->SetAttach($attch);
        $input->SetOut_trade_no($payments['order_nos']);
        $input->SetTotal_fee($payments['amount'] * 100);//订单金额以分为单位
//        $input->SetTotal_fee($order['totalfee'] * 100);//订单金额以分为单位
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
//        $input->SetGoods_tag("test");
        $input->SetNotify_url($notifyurl);
        $input->SetTrade_type($tradetype);
        $input->SetOpenid($openId);
//        var_dump($input);die;
        $config = new WxPayConfig();
        $config->appid = $wxconfig['AppID'];
        $config->secret = $wxconfig['AppSecret'];
        $config->mchid = $wxconfig['MchId'];
        $config->key = $wxconfig['MchKey'];
//        var_dump($config);die;
        $result = WxPayApi::unifiedOrder($config, $input);
        if (!empty($result["return_code"]) && strcasecmp($result["return_code"], "fail") === 0) {
            $msg = empty($result["return_msg"]) ? "发生错误，下单失败" : $result["return_msg"];
            $this->setError(-1,$msg);
            return false;
        }
        $tools  = new JsApiPay();
        try{
            $json_string = $tools->GetJsApiParameters($result,$config);
        } catch(WxPayException $e){
            $this->setError(-1,$e->errorMessage());
            return false;
        }
        $results = json_decode($json_string, true);
        $results["prepay_id"] = $result["prepay_id"];
//        dump($results);die;
        return $results;
    }

    function get_order_column($cond,$column)
    {
        $where = [];
        if(!empty($cond['orderids'])){
            $where[] = ['order_id','in',$cond['orderids']];
        }
        $rs = $this->where($where)->column($column);
        return $rs;
    }

//    h5支付成功回调处理
    function paysuccess($userinfo,$paymentsid,$payorderno,$backinfo, $payend){
		$paytime = time();
		Log::init([
			'path' => Env::get('runtime_path')."paylog/",
		]);

		$paywhere = [
			['user_id','=',$userinfo['user_id']],
			['payments_id','=',$paymentsid],
			['status','=',1],
		];
		$pay_data = [
			"status" => 2,
			"succeed_time" => $paytime,
			"trade_no" => $payorderno,
			"back_message" => $backinfo,
            "pay_end" => $payend,
		];
		$payModel = new Payments();
        $payModel->startTrans();
        $pay_rs = $payModel->where($paywhere)->update($pay_data);
        if($pay_rs === false){
            Log::record("购买记录更新失败","error");
            $payModel->rollback();
            return false;
        }

        $orderwhere = [
            ['o.user_id','=',$userinfo['user_id']],
            ['o.payments_id','=',$paymentsid],
        ];
        $order_data = [
            'order_status' => 2,
            'pay_status' => 2,
            'pay_time' => $paytime,
            'payorderno' => $payorderno,
            "pay_end" => $payend,
        ];
        $order_rs = $this->alias('o')->where($orderwhere)->update($order_data);
        if($order_rs === false){
            Log::record("订单状态修改失败","error");
            $payModel->rollback();
            return false;
        }

		$ofield = 'o.order_id,o.shop_id,o.order_type,o.order_time,o.orderno,o.address_id';
		$stmfield = 'stm.make_time,se.service_name';
		$sfield = 's.shop_phone';
		//查询订单信息
		$order = $this->alias('o')
			->field($ofield.','.$stmfield.','.$sfield)
			->where($orderwhere)
			->leftJoin([
				['ddt_service_team_middle stm','o.order_id = stm.order_id'],
				['ddt_service se','stm.service_id = se.service_id'],
				['ddt_shops s','o.shop_id = s.shop_id'],
			])
			->find();
//		print_r($order);die;

        $growModel = new GrowthLog();
        $Yunpian = new Yunpian();
		switch ($order['order_type']) {
			case 1;// 普通订单
                $data = $growModel->CalculateProfit($userinfo,$paymentsid,1);
                if(!$data){
                    Log::record("更新积分操作失败，msg：".$growModel->getError(),"error");
                    return false;
                }
				//发送短信
//				$rs = $Yunpian->SendNoticeOrder($order['shop_phone'],$order['orderno'],date("Y-m-d H:i:s", $order['order_time']),date("Y-m-d H:i:s", $paytime));
//				if($rs['code'] != 0){
//					Log::record("发送普通商品下单短信失败，msg：".$rs['msg'],"error");
//					$payModel->rollback();
//					return false;
//				}
				break;
			case 3;// 预约服务代码
                $data = $growModel->CalculateProfit($userinfo,$paymentsid,2);
                if(!$data){
                    Log::record("更新积分操作失败，msg：".$growModel->getError(),"error");
                    return false;
                }
				$middlewhere = [
					['order_id','=',$order['order_id']],
					['user_id','=',$userinfo['user_id']],
				];
				$middle_data = [
					'pay_state' => 2,
				];
				// 自动匹配街道团队
				$teamId = $this->ServiceTeam($order['shop_id'], $order['address_id']);
				if($teamId){
					$middle_data['team_id'] = $teamId;
				}

				$MiddleModel = new ServiceMiddle();
				$rs = $MiddleModel->where($middlewhere)->update($middle_data);
				if($rs === false){
					Log::record("预约服务表状态修改失败","error");
					$payModel->rollback();
					return false;
				}

				//发送短信
//				$rs = $Yunpian->SendNoticeservice($order['shop_phone'],$order['orderno'],$userinfo['nick_name'],$order['service_name'],$order['make_time']);
//				if($rs['code'] != 0){
//					Log::record("发送服务下单短信失败，msg：".$rs['msg'],"error");
//					$payModel->rollback();
//					return false;
//				}
				break;
		}

        $payModel->commit();
		$this->UserPushMessage($userinfo,$paymentsid);
		$this->UserPushMessage($userinfo,$paymentsid,false);
        return true;
    }

    // 服务团队匹配
    function ServiceTeam($shop_id,$address_id)
    {
        $TeamModel = new ServiceTeam();
        $addressModel = new Address();

        $address = $addressModel->getOne(['address_id' => $address_id],'area_id,street_id');

        $data = $TeamModel->getOne(['street_id' => $address['street_id'],'shop_id' => $shop_id],'team_id');
        if($data){
           return $data['team_id'];
        }
        return false;
    }

	//验证待支付订单商品和店铺(商品或者店铺下架则自动取消订单）
    function tobepaidordercheck($condition){
        $result = [
            "code" => -1,
            "msg" => '',
            "data" => [],
        ];
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $result['msg'] = '用户不存在该订单';
            return $result;
        }
        $order = $order->toArray();
//        var_dump($order);die;
        if($order['order_status'] != 1 || $order['pay_status'] != 1){
            $result['msg'] = '订单状态有误不允许取消';
            return $result;
        }

        $time = calculate([time(), $order['order_time']],'-',0);
        if($time > 1800){
            $result['msg'] = '订单已过期';
            return $result;
        }

        $item = 'od.*,s.shop_id,s.approved as s_approved,s.state as s_state,s.shop_type,p.is_del as p_del,p.state as p_state,p.approved as p_approved,ps.is_del as ps_del';
        $join = [
            ['ddt_order o','od.order_id = o.order_id'],
            ['ddt_shops s','o.shop_id = s.shop_id'],
            ['ddt_products p','od.product_id = p.product_id'],
            ['ddt_products_stock ps','od.p_s_id = ps.p_s_id'],
        ];
        $details = $this->api_order_details($order['order_id'],$item,$join);
        if(empty($details)){
            $result['msg'] = '订单商品数据有误';
            return $result;
        }
        $result['code'] = 1;
        $result['msg'] = '验证通过';
        $result['data'] = [
            'order' => $order,
            'details' => $details,
        ];
        if($details[0]['s_state'] != 1 || $details[0]['s_approved'] != 1){
            $result['code'] = 2;
            $result['msg'] = '该商铺已下架';
        }
        foreach($details as $value){
            if($value['ps_del'] != 1 || $value['p_del'] != 1 || $value['p_state'] != 1 || $value['p_approved'] != 2){
                $result['code'] = 2;
                $result['msg'] = '订单中部分商品已下架';
                break;
            }
        }
        return $result;
    }

//    更新订单为取消状态并回退库存
    function updateorderandstock($details,$order){
        $stockModel = new ProductStock();
        $this->startTrans();
        $stock_rs = $stockModel->batchstock($details,'+');
//        var_dump($stock_rs);
        if($stock_rs === false){
            $this->rollback();
            $this->setError(-1,$stockModel->getError());
            return false;
        }
        $param = [
            'order_status' => 5,
            'pay_status' => 3,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'操作失败');
            return false;
        }
        $this->commit();
        return true;
    }


    //  接口获取订单详情
    function api_order_details($orderId,$item = 'od.*',$join = [['ddt_order o','od.order_id = o.order_id'],['ddt_shops s','o.shop_id = s.shop_id']])
    {
        $detailModel = new \app\common\model\OrderDetail();
        $rs = $detailModel
            ->alias('od')
            ->leftJoin($join)
            ->field($item)
            ->where('od.order_id',$orderId)
            ->select()->toArray();
        return $rs;
    }



    /**
     * @param $make_time  预约时间
     * @param $address_id  地址ID
     * @param $service_id  服务ID
     * @param $quantity  数量
     * 服务下单
     */
    public function ServiceOrder($make_time, $address_id, $service_id, $quantity = 1,$user)
    {
        $SeviceModel = new Service();
        $PayMentModel = new Payments();
        $MiddleModel = new ServiceMiddle();
        $addressModel = new Address();


        if(!$make_time || !$address_id || !$service_id){
            $this->setError(-1,'请提交正确参数');
            return false;
        }

        // 获取服务数据
        $service = $SeviceModel->getOne(['service_id' => $service_id],'shop_id,price,sale_price');

        $address_data = $addressModel->getOne(['address_id' => $address_id],'name,phone,province_name,city_name,area_name,street_name,detail');

        $orderno = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

        // 支付表数据
        $payment = [
            'order_nos' => 'wx'.$orderno,
            'user_id' => $user['user_id'],
            'user_name' => $user['nick_name'],
            'amount' => calculate([$service['sale_price'],$quantity],'*',2),
            'payments_type' => 'service',
        ];
        // 订单表数据
        $order = [
            'shop_id' => $service['shop_id'],
            'order_type' => 3,
            'products_amount' => $service['price'],
            'coupon_amount' => 0,
            'express_fee' => 0,
            'order_amount' => calculate([$service['sale_price'],$quantity],'*',2),
            'pay_amount' => calculate([$service['sale_price'],$quantity],'*',2),
            'order_time' => time(),
            'orderno' => $orderno,
            'user_id' => $user['user_id'],
            'address_id' => $address_id,
            'receive_name' => $address_data['name'],
            'p_c_a' => $address_data['province_name'].' '.$address_data['city_name'].' '.$address_data['area_name'].' '.$address_data['street_name'] ,
            'r_address' => $address_data['detail'],
            'r_phone' => $address_data['phone'],
        ];

        // 预约服务数据
        $middle = [
            'service_id' => $service_id,
            'user_id' => $user['user_id'],
            'shop_id' => $service['shop_id'],
            'make_time' => $make_time,
            'quantity' => $quantity,
        ];

        // 开启事务
        $this->startTrans();

        $rs = true;
        try{

            $pay_id = $PayMentModel->insert($payment,'',true);
            if(!$pay_id){
                $rs = false;
            }
            $order['payments_id'] = $pay_id;

            $order_id = $this->insert($order,'',true);
            if(!$order_id){
                $rs = false;
            }

            $middle['order_id'] = $order_id;
            $maddle_id = $MiddleModel->insert($middle,'',true);
            if(!$maddle_id){
                $rs = false;
            }
            if($rs == false){
                $this->rollback();
                $this->setError(-1,'操作失败');
            }
            // 提交事务
            $this->commit();
        }catch (\Exception $e){
            $this->setError(-1,$e->getMessage());
            $this->rollback();
            return false;
        }
        $data = ['order_id' => $order_id, "send_id" => $maddle_id,"pay_id" => $pay_id];
        return $data;
    }



//    非购物车的下单验证（验证商品计算价格）
    function checkplace($user,$product_id,$stock_id,$quantity,$receive_id){
        $productModel = new Products();
        $item = "p.*,ps.p_s_id,ps.p_s_name,ps.stock";
        $product = $productModel->check_uncommon_product($product_id,$stock_id,$item);
        if($product === false){
            $this->setError(-1,$productModel->getError());
            return false;
        }
        if($product['stock'] < $quantity){
            $this->setError(-1,"该商品库存不足");
            return false;
        }
        if($product['class_id'] == 2){
            if($product['integral'] > $user['growth_coin']){
                $this->setError(-1,"用户积分不足以兑换该商品");
                return false;
            }
        }
        if($product['class_id'] == 3){
            $begintime = strtotime(date('Y-m-d').'00:00:00');;
            $endtime = strtotime(date('Y-m-d').'23:59:59');
            $orderModel = new \app\common\model\Order();
            $findtoday = $orderModel
                ->where('user_id','=',$user['user_id'])
                ->where('order_type','=',3)
                ->where('order_time','between',[$begintime,$endtime])
                ->find();
            if($findtoday){
                $this->setError(-1,"用户今日已领取免费爱心餐");
                return false;
            }
        }
        // 会员折扣
        $utype = 'mprice';
        $product['sale_price'] = $product[$utype];
        $data = [
            'productinfo' => $product,
            'coupon' => [],
        ];
        $utype = 'mprice';
        //商品总价
        $allproduct_amount = calculate([$product[$utype],$quantity],'*');
        //商品总积分
        $allpoints = calculate([$product['integral'],$quantity],'*',0);
        //订单使用优惠券减少的金额
        $allcoupon_amount = 0.00;
        //总运费
        $allexpress_fee = $product['express_fee'];
        //订单总价 = 商品总价-优惠券金额(不包含运费)
        $allorder_amount = 0.00;
        //优惠卷使用情况
        $is_coupon = true;

        if($receive_id){
            $CouponReceiveModel = new CouponReceive();
            $coupon = $CouponReceiveModel->where(['receive_id'=>$receive_id,'user_id'=>$user['user_id'],'is_use'=>1])->find();
            if(empty($coupon)){
                $this->setError(-1,"无效消费券");
                return false;
            }
            $coupon = $coupon->toArray();
            $data['coupon'] = $coupon;
            if($coupon && $allproduct_amount >= $coupon['fullmoney']){
                //计算订单使用优惠券减少的金额
                $allcoupon_amount = $coupon['discount'];
                //计算订单总价
                $allorder_amount = calculate([$allproduct_amount,$coupon['discount']],'-');
            } else {
                //计算订单使用优惠券减少的金额
                $allcoupon_amount = 0;
                //计算订单总价
                $allorder_amount = $allproduct_amount;
                $is_coupon = false;
//                $this->setError(-1,"未达使用要求");
//                return false;
            }
        } else {
            $allorder_amount = $allproduct_amount;
        }
        $pay_amount = calculate([$allorder_amount,$allexpress_fee],'+');
        $data['is_coupon'] = $is_coupon;
        $data['payinfo'] = [
            'allproduct_amount' => $allproduct_amount,
            'allpoints' => $allpoints,
            'allcoupon_amount' => $allcoupon_amount,
            'allexpress_fee' => $allexpress_fee,
            'allorder_amount' => $allorder_amount,
            'pay_amount' => $pay_amount,
        ];
        return $data;
    }



//    处理兑换商品订单插入数据
    function placeexchangeorder($user,$data,$quantity,$address){
        $detailModel = new \app\common\model\OrderDetail();
        $stockModel = new ProductStock();
        $time = time();
        $result = [
            'code' => false,
            'data' => [],
        ];

        $orderno = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);


        // 商品加起来的所需兑换总积分，
        $amount = calculate([$data['productinfo']['integral'],$quantity],'*',0);

        if($user['growth_coin'] < $amount){
            $this->setError(-1,'您所拥有的积分不足以兑换');
            return false;
        }


        // 订单数据
        $insertorder['shop_id'] = $data['productinfo']['shop_id'];
        $insertorder['order_amount'] = $data['productinfo']['integral'];
        $insertorder['pay_amount'] = $data['productinfo']['integral'];
        $insertorder['order_type'] = 2;
        $insertorder['pay_status'] = 2;
        $insertorder['order_status'] = 2;
        $insertorder['order_time'] = $time;
        $insertorder['orderno'] = $orderno;
        $insertorder['pay_time'] = $time;
        $insertorder['user_id'] = $user['user_id'];
        $insertorder['address_id'] = $address['address_id'];
        $insertorder['receive_id'] = 0;
        $insertorder['points'] = $amount;


        // 订单详情数据
        $insertdetail['user_id'] = $user['user_id'];
        $insertdetail['product_id'] = $data['productinfo']['product_id'];
        $insertdetail['product_name'] = $data['productinfo']['product_name'];
        $insertdetail['p_s_id'] = $data['productinfo']['p_s_id'];
        $insertdetail['p_s_name'] = $data['productinfo']['p_s_name'];
        $insertdetail['cover_url'] = $data['productinfo']['imageurl'];
        $insertdetail['quantity'] = $quantity;
        $insertdetail['price'] = $data['productinfo']['price'];
        $insertdetail['sale_price'] = $data['productinfo']['mprice'];
        $insertdetail['growth_coin'] = $data['productinfo']['integral'];
        $insertdetail['amount'] = calculate([$insertdetail['sale_price'],$quantity],'*',0);
        $insertdetail['growth_coin_amount'] = $amount;

        // 开启事务
        $this->startTrans();

        try{
            $orderid = $this->insert($insertorder,'',true);

            if($orderid === false){
                $this->rollback();
                $this->setError(-1,'订单生成失败');
                return $result;
            }

            $insertdetail['order_id'] = $orderid;

            $res = $detailModel->insertorderdetail($insertdetail);
            if($res === false){
                $this->rollback();
                $this->setError(-1,'订单商品信息记录失败');
                return $result;
            }

            // 更改库存
            $reduce_rs = $stockModel->reducestock($data['productinfo']['product_id'],$data['productinfo']['p_s_id'],$quantity);
            if($reduce_rs === false){
                $this->rollback();
                $this->setError(-1,'商品库存减少失败');
                return false;
            }
            // 更改积分
            $userModel = new User();
            $user_rs = $userModel->reducepoints($user,$amount);
            if($user_rs === false){
                $this->rollback();
                $this->setError(-1,'用户积分减少失败');
                return false;
            }

            // 提交
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->setError(-1, $e->getMessage());
            $this->rollback();
            return false;
        }
    }



    function get_Service_Order_list($cond, $orderby, $item, $page = "1", $limit = "10", $is_page = "1")
    {

        $where = null;

        if(!empty($cond['order_type'])){
            $where[] = ['a.order_type', '=', $cond['order_type']];
        }

        if(!empty($cond['send_id'])){
            $where[] = ['b.send_id', '=', $cond['send_id']];
        }
        if(!empty($cond['order_id'])){
            $where[] = ['b.order_id', '=', $cond['order_id']];
        }

        if(!empty($cond['state'])){
            if($cond['state'] == 1){
                $where[] = ['b.state', 'in', "1,2"];
            }else{
                $where[] = ['b.state', 'in', "3,4,5"];
            }
        }

        if(!empty($cond['shop_id'])){
            $where[] = ['a.shop_id', '=', $cond['shop_id']];
        }

        if(!empty($cond['user_id'])){
            $where[] = ['a.user_id', '=', $cond['user_id']];
        }

//        if(!empty($cond['pay_status'])){
//            $where[] = ['a.pay_status', '=', $cond['pay_status']];
//        }

        if(!empty($cond['order_status'])){
            $where[] = ['a.order_status', '=', $cond['order_status']];
        }

        $where[] = ['pay_state','=',2];

        $rs = Db::table($this->table)
            ->alias('a')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->leftJoin('ddt_service_team_middle b','a.order_id = b.order_id')
            ->leftJoin('ddt_service c', 'b.service_id = c.service_id')
            ->leftJoin('ddt_service_team d','b.team_id = d.team_id');
        if($is_page == 2){
            $rs = $rs->page($page, $limit);
        }

            $rs = $rs->select();
        return $rs;
    }



    function getJoinOrder($where=[1], $item='o.*',$join = [['ddt_shops s','o.shop_id = s.shop_id']])
    {
        $rs = $this
            ->alias('o')
            ->join($join)
            ->field($item)
            ->where($where)
            ->find();
        return $rs;
    }


//    用户评价操作
    function operatecomment($condition,$params,$pic_number = 3){
        $where[] = ['o.order_id','=',$condition['order_id']];
        $where[] = ['o.user_id', '=', $condition['user_id']];
        $where[] = ['od.detail_id', '=', $condition['detail_id']];
        if(empty($params['content'])){
            $this->setError(-1,'必填项不能为空');
            return false;
        }


        if(!is_array($params['images'])){
            $params['images'] = explode(',',$params['images']);
        }

        if(count($params['images']) > $pic_number){
            $this->setError(-1,"上传图片不能超过{$pic_number}张");
            return false;
        }
        $item = 'o.*,od.detail_id,ps.*';
        $join = [
            ['ddt_orderdetail od','o.order_id = od.order_id'],
            ['ddt_products_stock ps','od.p_s_id = ps.p_s_id'],
        ];
        $order = $this->getJoinOrder($where,$item,$join);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        if($order['order_status'] != 4 || $order['pay_status'] != 2){
            $this->setError(-1,'该订单还未完成不能评价');
            return false;
        }
        $stock_info = [
            "p_s_id" => $order['p_s_id'],
            "p_s_name" => $order['p_s_name'],
            "stock" => $order['stock'],
            "product_id" => $order['product_id'],
            "order_time" => $order['order_time'],
        ];
//        var_dump($stock_info);die;
        $data = [
            'content' => $params['content'],
            'star' => 5,
            'user_id' => $order['user_id'],
            'product_service_id' => $order['product_id'],
            'order_detail_id' => $order['detail_id'],
            'proterty_details' => json_encode($stock_info,true),
            'order_id' => $order['order_id'],
            'images' => implode(',',array_filter($params['images'])),
        ];
        $commitModel = new Commit();
        $this->startTrans();
        $rs = $commitModel->edit($data);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'插入记录失败');
            return false;
        }

        $rs = $this->where('order_id', $condition['order_id'])->update(['is_comment' => 1]);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'更新评价状态失败');
            return false;
        }

        $detailModel = new OrderDetail();
        $rs = $detailModel->edit(['is_comment' => 1],$order['detail_id']);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'更新评价状态失败');
            return false;
        }
        $this->commit();
        return true;
    }


//    用户评价操作
    function operateaftersales($condition,$params,$pic_number = 3){
        $where[] = ['o.order_id','=',$condition['order_id']];
        $where[] = ['o.user_id', '=', $condition['user_id']];
        $where[] = ['od.detail_id', '=', $condition['detail_id']];
        if(empty($params['content'])){
            $this->setError(-1,'必填项不能为空');
            return false;
        }

		if(!is_array($params['images'])){
			$params['images'] = explode(',',$params['images']);
		}

        if(count($params['images']) > $pic_number){
            $this->setError(-1,"上传图片不能超过{$pic_number}张");
            return false;
        }
        $afterModel = new Aftersales();
        $after = $afterModel->getOne([['user_id','=',$condition['user_id']],['order_detail_id','=',$condition['detail_id']]]);
//        var_dump($after);die;
        if($after){
            $this->setError(-1,'该商品已申请售后，请等待客服联系');
            return false;
        }
        $item = 'od.*,o.shop_id,o.order_status,o.pay_status,o.orderno,o.order_time,o.pay_time,o.order_type,ps.*';
        $join = [
            ['ddt_orderdetail od','o.order_id = od.order_id'],
            ['ddt_products_stock ps','od.p_s_id = ps.p_s_id'],
        ];
        $order = $this->getJoinOrder($where,$item,$join);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
//        var_dump($params);
//        var_dump($order);die;
        if($order['order_status'] != 4 && $order['pay_status'] != 2){

            $this->setError(-1,'该订单还未完成不能申请售后');
            return false;
        }

        // 改变订单状态
        $rs = $this->where('order_id', $order['order_id'])->update(['order_status' => 10]);
        if($rs === false){
            $this->setError(-1,'改变订单状态失败');
            return false;
        }

        $data = [
            'content' => $params['content'],
            'images' => implode(',',array_filter($params['images'])),
            'user_id' => $order['user_id'],
            'order_id' => $order['order_id'],
            'order_detail_id' => $order['detail_id'],
            'product_id' => $order['product_id'],
            'stock_id' => $order['p_s_id'],
            'order_product_details' => json_encode($order->toArray(),true),
            'shop_id' => $order['shop_id'],
			'is_status' => $params['is_status'],
        ];
//        var_dump($data);die;
        $rs = $afterModel->edit($data);
        if($rs === false){
            $this->setError(-1,$afterModel->getError());
            return false;
        }
        return true;
    }


//    操作确认订单
    function operatesure($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
        if($order['order_status'] != 3 || $order['pay_status'] != 2){
            $this->setError(-1,'订单状态有误不允许操作');
            return false;
        }
        $param = [
            'order_status' => 4,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->setError(-1,'操作失败');
            return false;
        }
        return true;
    }



//    取消售后订单
    function userafters($condition){
        $AfterModel = new Aftersales();
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
        if($order['order_status'] != 10 || $order['pay_status'] != 2){
            $this->setError(-1,'订单状态有误不允许操作');
            return false;
        }
        $param = [
            'order_status' => 4,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);

        $rs1 = $AfterModel->where('order_id', $condition['order_id'])->delete();

        if($rs === false || $rs1 === false){
            $this->setError(-1,'操作失败');
            return false;
        }
        return true;
    }


//    操作确认提醒发货
    function operateremind($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
        if($order['is_remind'] == 2){
            $this->setError(-1,'该订单已提醒');
            return false;
        }
        if($order['order_type'] != 1 && $order['order_type'] != 2){
            $this->setError(-1,'订单类型有误');
            return false;
        }
        if($order['order_status'] != 2 || $order['pay_status'] != 2){
            $this->setError(-1,'订单状态有误');
            return false;
        }
        $param = [
            'is_remind' => 2,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->setError(-1,'操作失败');
            return false;
        }
        return true;
    }


//    操作取消订单
    function operatecancel($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
//        var_dump($order);die;
        if($order['order_status'] != 1 || $order['pay_status'] != 1){
            $this->setError(-1,'订单状态有误不允许取消');
            return false;
        }
        $item = 'od.*';
        $join = [
            ['ddt_order o','od.order_id = o.order_id'],
        ];
        $details = $this->api_order_details($order['order_id'],$item,$join);
//        var_dump($details);die;
        if(empty($details)){
            $this->setError(-1,'订单商品数据有误');
            return false;
        }
        $rs = $this->updateorderandstock($details,$order);
        return $rs;
    }

//    用户消息推送
    public function UserPushMessage($userinfo,$paymentid,$is_user = true)
    {
        $config = config::pull('weixin_applet');
        $messagepush = config::pull('messagepush');

        $where = [
            ['user_id', '=', $userinfo['user_id']],
            ['payments_id', '=',$paymentid],
        ];
        $order = $this->getOne($where);
        $string = '';
        $template_id = $messagepush['pushuser'];
        if($is_user){
            $openid = $userinfo['applets_openid'];
        } else {
            $openid = 'o8-0N5DqU3lGt-GMaZw3qrzo2J3k';
        }
        if($order['order_type'] != 3){
            $item = 'od.*,s.shop_id';
            $detail = $this->api_order_details($order['order_id'], $item);
            foreach($detail as $value){
                !empty($string)? $string .= "，":'';
                $string .= "{$value['product_name']}({$value['p_s_name']}) X {$value['quantity']}";
            }
//            echo $this->getLastSql();
//            var_dump($detail);die;
        } else {
            $cond['order_id'] = $order['order_id'];
            $field = "a.order_id,a.is_comment,a.address_id,a.receive_name,a.p_c_a,a.r_address,a.r_phone,a.order_status,a.orderno,a.pay_status,a.order_status,a.pay_amount,a.pay_time,b.make_time,b.send_id,b.state,b.service_id,c.service_name,c.top_pic,d.team_name,d.phone";
            $detail = $this->get_Service_Order_list($cond,'',$field);
            foreach($detail as $value){
                !empty($string)? $string .= "，":'';
                $string .= $value['service_name'];
            }
        }
        $data = [
            'character_string3' => [
                "value" => $order['orderno'],
            ],// 订单编号
            'amount10' => [
                "value" => $order['pay_amount'],
            ],//订单金额
            'thing4' => [
                "value" => $string,
            ],//服务内容
            'thing1' => [
                "value" => $order['p_c_a'].$order['r_address'],
            ],//订单地址
            'phone_number19' => [
                "value" => $order['r_phone'],
            ],//联系电话
        ];
//        var_dump($userinfo);die;
        try{
            $rs = Wechat::messagepush($config,$openid,$template_id,'',$data);
        }catch (\Exception $e){
            return $e->getMessage();
        }
        return $rs;
    }
}